<?php

class Controller_Signin extends Controller_Website
{

    public function before() {
        parent::before();
        $this->mod = Model::factory('directory');
        $this->man = Model::factory('manager');
        $this->section = 'signin';
    }

	public function actionIndex()
	{
//        system::dump($_SESSION);exit();
        $this->template->hideFooter=1;
		$this->template->content = new View('signin/index');

        $form = new Form('signin');
        $form->text('email', 'Name')->rule('email')->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->password('password', 'Password')->rule('maxLength', 32)->attribute('size', 24)->rule('required');
        $form->checkbox('persistent', '', 'Stay signed in');
        $form->submit('submit', 'Sign In');

        $form2 = new Form('register');
        $form2->text('email', 'Name')->rule('email')->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form2->password('password', 'Password')->rule('maxLength', 32)->attribute('size', 24)->rule('required');
        $form2->password('name', 'Password')->rule('maxLength', 32)->attribute('size', 24)->rule('required');
        $form2->password('surname', 'Password')->rule('maxLength', 32)->attribute('size', 24)->rule('required');
        $form2->checkbox('persistent', '', 'Stay signed in');
        $form2->submit('submit', 'Sign In');

        if (Request::$method == 'POST') {
            if ($form->validate()) {
                $values = $form->getValues();
                    if (Auth::getInstance()->authenticateMail($values['email'], $values['password'], $values['persistent'])) {
                        $this->response->redirect('/account/');
                    } else {
                        echo '<script type="text/javascript">alert("This user is not registered.")</script>';
                    }
            }elseif($form2->validate()){
                $values = $form2->getValues();
                if (Auth::getInstance()->registerMail($values['email'], $values['password'], $values['name'], $values['surname'])) {
                    Auth::getInstance()->authenticateMail($values['email'], $values['password']);
                    $this->man->selectMember($_SESSION['identity']['id'],$values['name'],$values['surname']);
                    $this->response->redirect('/account/');
                } else {
                    echo '<script type="text/javascript">alert("Alredy in db.")</script>';
                }
            }
        }

        $this->template->content->form = $form;
        $this->template->content->form2 = $form2;
	}
    public function actionOut()
    {
        {
            if (isset($_SESSION['identity'])) {
                unset($_SESSION['identity']);
            }
            session_regenerate_id(true);
        }
        $this->response->redirect('/signin/');
    }
}